﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;

namespace SoftSource.Reactive
{
    /// <summary>
    /// These wrap some useful Silverlight UI events.
    /// </summary>
    public static class ReactiveUIExtensions
    {
        public static IObservable<IEvent<DataGridBeginningEditEventArgs>> WhenBeginningEdit(this DataGrid dataGrid)
        {
            return Observable.FromEvent<DataGridBeginningEditEventArgs>(
                handler => dataGrid.BeginningEdit += handler,
                handler => dataGrid.BeginningEdit -= handler);
        }

        public static IObservable<IEvent<DataGridRowEventArgs>> WhenLoadingRow(this DataGrid dataGrid)
        {
            return Observable.FromEvent<DataGridRowEventArgs>(
                handler => dataGrid.LoadingRow += handler,
                handler => dataGrid.LoadingRow -= handler);
        }
        public static IObservable<IEvent<MouseButtonEventArgs>> WhenDoubleClick(this UIElement ui)
        {
            return ReactiveUIExtensions.WhenDoubleClick(ui, TimeSpan.FromSeconds(0.3));
        }

        public static IObservable<IEvent<MouseButtonEventArgs>> WhenDoubleClick(this UIElement ui, TimeSpan clickInterval)
        {
            var mouseLeftDown = Observable.FromEvent<MouseButtonEventHandler, MouseButtonEventArgs>(
                handler => (sender2, e2) => handler(sender2, e2),
                handler => ui.MouseLeftButtonDown += handler,
                handler => ui.MouseLeftButtonDown -= handler);

            var doubleClick = from md in mouseLeftDown.TimeInterval()
                              where md.Interval < clickInterval
                              select md.Value;

            return doubleClick;
        }
    }
}
